package com.cino.strategy.impl;

import com.cino.annotation.ConditionalOnListProperty;
import com.cino.entity.SysAuditLog;
import com.cino.service.AsyncAuditLogService;
import com.cino.strategy.AuditLogStorageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * MySQL审计日志存储策略实现
 * 
 * 使用@ConditionalOnListProperty注解，当配置中支持mysql时加载，或作为保底策略
 * 配置路径：ys.log.storage.supports，期望值：mysql
 * matchIfMissing=true：当配置不存在时也加载，作为默认保底策略
 */
@Slf4j
@Component
@ConditionalOnListProperty(name = "ys.log.storage.supports", havingValue = "mysql", matchIfMissing = true)
public class MysqlAuditLogStorageStrategy implements AuditLogStorageStrategy {
    
    @Autowired
    private AsyncAuditLogService asyncAuditLogService;
    
    @Override
    public void saveAuditLog(SysAuditLog sysAuditLog) {
        try {
            // 直接使用现有的AsyncAuditLogService
            asyncAuditLogService.saveAuditLogAsync(sysAuditLog);
            
            log.info(">>> [MySQL策略] 已提交审计日志到AsyncAuditLogService");
                
        } catch (Exception e) {
            log.error(">>> [MySQL策略] 审计日志保存失败: {}", e.getMessage(), e);
            throw e;
        }
    }
    
    @Override
    public void saveAuditLog(String objectId, String objectType, String content, String operationType, String storageTable,
                             Integer auditStatus, String errorMessage, Long duration, String title) {
        try {
            // 使用AsyncAuditLogService的新方法（支持新增字段）
            asyncAuditLogService.saveAuditLogAsync(objectId, objectType, content, operationType, storageTable, 
                                                 auditStatus, errorMessage, duration, title);
            
            log.info(">>> [MySQL策略] 已提交审计日志到AsyncAuditLogService，表名: {}，状态: {}", storageTable, auditStatus);
            
        } catch (Exception e) {
            log.error(">>> [MySQL策略] 审计日志保存失败: {}", e.getMessage(), e);
            throw e;
        }
    }
    
    @Override
    public String getStrategyType() {
        return "mysql";
    }
    
    @Override
    public boolean isAvailable() {
        try {
            // 检查AsyncAuditLogService是否可用
            return asyncAuditLogService != null;
        } catch (Exception e) {
            log.warn(">>> [MySQL策略] 可用性检查失败: {}", e.getMessage());
            return false;
        }
    }
}
